package com.example.boot.rabbitmq.producer.boot.config.delay;

import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;


/**
 * 延迟队列方式一 使用 queue 方法配置死信队列信息
 * delay 配置 正常交换器为 direct 类型 交换器严格匹配路由键
 * @author root
 * @date 2021-03-06 14:21
 */
//@Configuration
@RequiredArgsConstructor
public class RabbitDelayConfig {


    private final RabbitDelayProperties rabbitDelayProperties;

    /**
     * 配置 direct 类型交换器
     * @return 交换器
     */
    @Bean
    public DirectExchange directNormalExchange(){
        return new DirectExchange(rabbitDelayProperties.getNormalExchange());
    }

    /**
     * 声明一个持久化的队列 并且设置过期时间 死信队列信息
     * @return 声明队列
     */
    @Bean
    public Queue directNormalQueue() {
        return QueueBuilder.durable(rabbitDelayProperties.getNormalQueue())
                .ttl(5000)
                .deadLetterExchange(rabbitDelayProperties.getDelayExchange())
                .deadLetterRoutingKey(rabbitDelayProperties.getDelayKey())
                .build();
    }

    /**
     * 队列交换机绑定
     * @param directNormalExchange 交换器
     * @param directNormalQueue 队列
     * @return 绑定信息
     */
    @Bean
    public Binding directNormalBinding(DirectExchange directNormalExchange, Queue directNormalQueue) {
        return BindingBuilder
                .bind(directNormalQueue)
                .to(directNormalExchange)
                .with(rabbitDelayProperties.getDelayKey())
                ;
    }



    /**
     * 配置 delay 类型交换器
     * @return 交换器
     */
    @Bean
    public DirectExchange delayExchange(){
        return new DirectExchange(rabbitDelayProperties.getDelayExchange());
    }

    /**
     * 声明一个持久化的队列
     * @return 声明队列
     */
    @Bean
    public Queue delayQueue() {
        return QueueBuilder.durable(rabbitDelayProperties.getDelayQueue()).build();
    }

    /**
     * 队列交换机绑定
     * @param delayExchange 交换器
     * @param delayQueue 队列
     * @return 绑定信息
     */
    @Bean
    public Binding delayBinding(DirectExchange delayExchange, Queue delayQueue) {
        return BindingBuilder.bind(delayQueue)
                .to(delayExchange)
                .with(rabbitDelayProperties.getDelayKey());
    }



}
